﻿package javase.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public class SaxXmlParse {
	public static void main(String[] args) {
		SAXParserFactory spf = SAXParserFactory.newInstance();
		try {
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();
			/** 注册事件监听器 */
			xr.setContentHandler(new SAXCounter());
			/** 解析 */
//			xr.parse(new InputSource(new FileInputStream("src/com/javase/xml/demo/FirstXml.xml")));
			sp.parse(new FileInputStream("src/com/javase/xml/demo/FirstXml.xml"), new SAXCounter());
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

/** 统计一个xml文档中的各个标签数量 */
class SAXCounter extends DefaultHandler {

	/** 以名值对的形式存放 tagName - count */
	private HashMap<String, Integer> hm;

	@Override
	public void startDocument() throws SAXException {
		System.out.println("start parse xml...");
		hm = new HashMap<String, Integer>();
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		//qName是标签名
		String key = qName;
		Integer value = hm.get(key);
		if (value == null) {
			hm.put(key, new Integer(1));
		} else {
			value = hm.get(key).intValue();
			value++;
			hm.put(key, new Integer(value));
		}
	}

	@Override
	public void endDocument() throws SAXException {
		Set<Map.Entry<String, Integer>> s = hm.entrySet();
		Iterator<Map.Entry<String, Integer>> it = s.iterator();
		while (it.hasNext()) {
			Map.Entry<String, Integer> me = it.next();
			String tagName = me.getKey();
			Integer tagCount = me.getValue();
			System.out.println("tagName:" + tagName + " count:" + tagCount);
		}
	}
	
}
